using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniAspNetCore
{
    /// <summary>
    /// 应用构建者
    /// </summary>
    public class ApplicationBuilder : IApplicationBuilder
    {
        /// <summary>
        /// 缓存中间件
        /// </summary>
        private readonly List<Func<RequestDelegate, RequestDelegate>> _middlewares = new List<Func<RequestDelegate, RequestDelegate>>();

        /// <summary>
        /// 构建中间件管道
        /// </summary>
        /// <returns>中间件管道</returns>
        public RequestDelegate Build() => httpContext => 
        {
            RequestDelegate next = _ => Task.Run(() => _.Response.StatusCode = 404); // 兜底中间件

            // 逆序构建中间件管道
            Func<RequestDelegate, RequestDelegate>[] middlewares = _middlewares.ToArray();
            for (int index = middlewares.Length - 1; index >= 0; index--)
            {
                next = middlewares[index](next);
            }

            return next(httpContext);
        };

        /// <summary>
        /// 注册中间件
        /// </summary>
        /// <param name="middleware">中间件</param>
        /// <returns>应用构建者</returns>
        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _middlewares.Add(middleware);
            return this;
        }
    }
}
